#!/bin/bash

VAR_SLEEP="10"
VAR_DOCKERNAME="sogou:2.21"


# ------------------------------------------------------

function echotime {
  VAR_DATE=`date +%Y-%m-%d%t%H:%M:%S`
  echo " "
  echo ${VAR_DATE}
}

function startpy {
  while true
    do
      echotime
      echo "执行./app/start.py"
      python ./app/start.py
      echotime
      echo "项目执行完成，暂停[${VAR_SLEEP}]秒"
      sleep $VAR_SLEEP
    done
}

function initpython {
    docker_install
    echo "正在拉取工程代码django-python"
    git clone https://gitee.com/degao/docker-python.git temp
    cp -R temp/* ./
    rm -rf temp
    echo "正在建立venv虚拟环境,目录：venv"
    python3 -m venv venv
    echo "进入venv环境，安装django必要库"
    source ./venv/bin/activate
    pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt
    startpy
}

function dockercompose {
    docker_install
    echo "正在构建本地Docker容器，构建完成后启动容器"
    echo "第一次构建大概要15分钟左右"
    docker-compose up --build --force-recreate
}

function dockerbuild {
    docker_install
    echo "正在创建容器镜像"
    docker build -t baiyea/${VAR_DOCKERNAME} .
}

function docker_install()
{
	echo "检查Docker......"
	docker -v
    if [ $? -eq  0 ]; then
        echo "检查到Docker已安装!"
    else
    	echo "安装docker环境..."
        curl -sSL https://get.daocloud.io/docker | sh
        echo "安装docker环境...安装完成!"
    fi
}

function python3_check()
{
	echo "检查Python3环境......"
	python3 -V
    if [ $? -eq  0 ]; then
        echo "Python3已安装!"
    else
        echo "未检测到 python3 环境"
        exit
    fi
}

function menu {
    clear
    echo "please select"
    echo "1. 启动项目"
    echo "2. 安装单脚本框架"
    echo "3. docker-compose up --force-recreate (上线部署前执行)"
    echo "4. 打包Docker镜像名称为：${VAR_DOCKERNAME}"
    echo "Enter an option: "
    read -n 1 option
}

if [[ $1 == "dev" ]]
then
  while [ 1 ]
  do
      menu
      case $option in
      0)
          break ;;
      1)
          startpy ;;
      2)
          initpython ;;
      3)
          dockercompose ;;
      4)
          dockerbuild ;;
      *)
          clear
          echo "Sorry, 重新选择" ;;
      esac
      echo "按任意键回到菜单"
      read -n 1 line
  done
  clear
fi

startpy